<template>
  <div class="blog-search-container">
    <div class="nav">
        <Nav/>
    </div>
    <!-- 搜索区域 -->
    <div class="search-area">
      <div class="search-wrapper">
        <div class="search-input-container">
          <input
            v-model="searchQuery"
            type="text"
            placeholder="请输入搜索内容"
            @input="handleInput"
            @focus="showSuggestions = true"
            @blur="hideSuggestionsDelayed"
            class="search-input"
          />
          <button @click="searchArticles" class="search-button">
            <i class="el-icon-search"></i> 搜索
          </button>
          <!-- 搜索建议下拉框 -->
          <div 
            v-show="showSuggestions && searchSuggestions.length > 0"
            class="search-suggestions"
          >
            <ul>
              <li
                v-for="(suggestion, index) in searchSuggestions"
                :key="index"
                @click="handleSuggestionClick(suggestion)"
              >
                {{ suggestion }}
              </li>
            </ul>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 搜索结果区域 -->
    <div class="result-area" v-show="showResults">
      <div class="filter-options">
        <div class="filter-type">
          <button
            :class="{ active: searchType === 'article' }"
            @click="searchType = 'article'"
          >
            文章
          </button>
          <button
            :class="{ active: searchType === 'user' }"
            @click="searchType = 'user'"
          >
            用户
          </button>
          <button
            :class="{ active: searchType === 'tag' }"
            @click="searchType = 'tag'"
          >
            标签
          </button>
        </div>
      </div>
      
      <!-- 文章卡片列表 -->
      <div class="article-list">
        <div
          class="article-card"
          v-for="article in articles"
          :key="article.id"
        >
          <div class="article-header">
            <img :src="article.author.avatar" alt="作者头像" class="author-avatar" />
            <div class="author-info">
              <span class="author-name">{{ article.author.name }}</span>
              <span class="publish-time">{{ formatDate(article.publishTime) }}</span>
            </div>
            <span v-if="article.isTop" class="top-tag">置顶</span>
            <span v-if="article.isRecommend" class="recommend-tag">推荐</span>
          </div>
          <h3 class="article-title" @click="goToArticle(article.id)">{{ article.title }}</h3>
          <p class="article-summary">{{ article.summary }}</p>
          <div class="article-meta">
            <span v-for="tag in article.tags" :key="tag" class="tag">{{ tag }}</span>
            <span class="view-count">
              <i class="el-icon-view"></i> {{ article.viewCount }}
            </span>
            <span class="like-count">
              <i class="el-icon-like"></i> {{ article.likeCount }}
            </span>
            <span class="comment-count">
              <i class="el-icon-chat-line-round"></i> {{ article.commentCount }}
            </span>
          </div>
        </div>
        
        <!-- 加载更多 -->
        <div class="load-more" v-if="hasMore">
          <button @click="loadMore" class="load-more-btn">加载更多</button>
        </div>
        
        <!-- 没有更多结果 -->
        <div class="no-more-results" v-else>
          <p>已经到底了哦~</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, watch, onBeforeUnmount } from 'vue';
import router from '@/router.js';
import Nav from '@/views/Layout/nav.vue';
import Hot from '../Layout/hot.vue'

// 搜索相关数据
const searchQuery = ref('');
const searchSuggestions = ref([]);
const showSuggestions = ref(false);
const showResults = ref(false);
const searchType = ref('article');

// 文章列表相关数据
const articles = ref([]);
const page = ref(1);
const pageSize = ref(10);
const total = ref(0);
const hasMore = ref(true);
const isLoading = ref(false);

// 防抖定时器
let debounceTimer = null;

// 格式化日期
const formatDate = (dateStr) => {
  const date = new Date(dateStr);
  return date.toLocaleDateString();
};

// 输入处理 - 获取搜索建议
const handleInput = () => {
  console.log('进入搜索建议逻辑');
  const value = searchQuery.value; // 直接从 ref 获取值
  if (debounceTimer) {
    clearTimeout(debounceTimer);
  }
  
  debounceTimer = setTimeout(() => {
    if (value.trim() === '') {
      searchSuggestions.value = ["文章1","文章2","文章3"];
      return;
    }
    
    // 模拟调用搜索建议接口
    console.log(`调用搜索建议接口: /api/search/suggestions?query=${value}`);
    
    // 模拟接口返回数据
    searchSuggestions.value = [
      `${value}教程`,
      `${value}入门`,
      `${value}高级应用`,
      `最新${value}技术`,
      `实战${value}项目`
    ];
    showSuggestions.value = true;
  }, 300);
  console.log(showSuggestions.value);
  console.log(searchSuggestions.value);
};

// 延迟隐藏搜索建议
const hideSuggestionsDelayed = () => {
  setTimeout(() => {
    showSuggestions.value = false;
  }, 200);
};

// 处理搜索建议点击
const handleSuggestionClick = (suggestion) => {
  searchQuery.value = suggestion;
  searchArticles();
};

// 搜索文章
const searchArticles = () => {
  if (searchQuery.value.trim() === '') {
    return;
  }
  
  // 重置分页
  page.value = 1;
  hasMore.value = true;
  
  // 模拟调用搜索文章接口
  console.log(`调用搜索文章接口: /api/search/articles?query=${searchQuery.value}&type=${searchType.value}&page=${page.value}&pageSize=${pageSize.value}`);
  
  // 模拟接口返回数据
  const mockArticles = generateMockArticles(10);
  
  articles.value = mockArticles;
  total.value = 50; // 模拟总共有50条结果
  showResults.value = true;
  showSuggestions.value = false;
  
  // 检查是否还有更多数据
  hasMore.value = articles.value.length < total.value;
};

// 加载更多文章
const loadMore = () => {
  if (isLoading.value || !hasMore.value) return;
  
  isLoading.value = true;
  page.value++;
  
  // 模拟调用搜索文章接口获取下一页数据
  console.log(`调用搜索文章接口: /api/search/articles?query=${searchQuery.value}&type=${searchType.value}&page=${page.value}&pageSize=${pageSize.value}`);
  
  // 模拟接口返回数据
  const mockArticles = generateMockArticles(10);
  
  // 延迟1秒，模拟网络请求时间
  setTimeout(() => {
    articles.value = [...articles.value, ...mockArticles];
    total.value = 50; // 模拟总共有50条结果
    
    // 检查是否还有更多数据
    hasMore.value = articles.value.length < total.value;
    isLoading.value = false;
  }, 1000);
};

// 跳转到文章详情页
const goToArticle = (articleId) => {
  console.log(`跳转到文章详情页: 文章ID=${articleId}`);
  router.push({ name: 'ArticleDetail', params: { id: articleId } });
};

// 监听搜索类型变化
watch(searchType, () => {
  if (searchQuery.value.trim() !== '') {
    searchArticles();
  }
});

// 生成模拟文章数据
const generateMockArticles = (count) => {
  const articles = [];
  const titles = [
    '深入理解Vue3响应式原理',
    '前端性能优化的10个实用技巧',
    'JavaScript异步编程全解析',
    'TypeScript高级类型实战应用',
    'React与Vue的对比分析',
    '微前端架构设计与实践',
    'Webpack5配置优化指南',
    'Node.js性能调优秘籍',
    'CSS Grid布局完全指南',
    '前端工程化最佳实践'
  ];
  
  const summaries = [
    '本文详细讲解了Vue3响应式原理的底层实现机制，帮助开发者更好地理解和使用Vue3。',
    '分享10个实用的前端性能优化技巧，从代码到构建再到部署全方位提升网站性能。',
    '深入探讨JavaScript异步编程的各种实现方式，包括回调函数、Promise、async/await等。',
    '介绍TypeScript高级类型的使用方法和场景，帮助你编写更健壮、更具表现力的代码。',
    '从多个维度对比分析React和Vue这两大前端框架的优缺点，帮助你在项目中做出更好的选择。',
    '讲解微前端架构的设计理念和实现方式，以及如何在实际项目中应用微前端技术。',
    '详细介绍Webpack5的新特性和配置优化方法，让你的项目构建速度提升50%以上。',
    '分享Node.js性能调优的经验和技巧，包括内存管理、异步处理、集群模式等方面。',
    '全面讲解CSS Grid布局的概念和用法，让你轻松实现复杂的网页布局。',
    '介绍前端工程化的最佳实践，包括项目结构、构建流程、代码规范、测试部署等方面。'
  ];
  
  const tagsList = [
    ['Vue3', '前端框架', '响应式'],
    ['性能优化', '前端', 'Webpack'],
    ['JavaScript', '异步编程', 'Promise'],
    ['TypeScript', '高级类型', '静态类型'],
    ['React', 'Vue', '前端框架'],
    ['微前端', '架构设计', '前端'],
    ['Webpack5', '构建工具', '前端工程化'],
    ['Node.js', '性能调优', '后端'],
    ['CSS Grid', '布局', 'CSS'],
    ['前端工程化', '最佳实践', '开发流程']
  ];
  
  for (let i = 0; i < count; i++) {
    const randomIndex = Math.floor(Math.random() * titles.length);
    const isTop = i % 10 === 0; // 10%的文章设为置顶
    const isRecommend = i % 5 === 0; // 20%的文章设为推荐
    
    articles.push({
      id: i + 1,
      title: titles[randomIndex],
      summary: summaries[randomIndex],
      author: {
        name: `作者${Math.floor(Math.random() * 100)}`,
        avatar: 'https://picsum.photos/40/40?random=' + i
      },
      publishTime: new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000).toISOString(),
      tags: tagsList[randomIndex],
      viewCount: Math.floor(Math.random() * 10000),
      likeCount: Math.floor(Math.random() * 1000),
      commentCount: Math.floor(Math.random() * 100),
      isTop,
      isRecommend
    });
  }
  
  return articles;
};

// 组件销毁前清理定时器
onBeforeUnmount(() => {
  if (debounceTimer) {
    clearTimeout(debounceTimer);
  }
});

// 初始化
onMounted(() => {
  // 可以在这里添加一些初始化逻辑
  console.log('博客搜索页面初始化完成');
});
</script>

<style scoped>
.blog-search-container {
  min-height: 100vh;
  background-color: #c7b5b5;
}

.search-area {
  padding: 60px 0;
  /* background-color: #c7b5b5; */
  /* background-color: #fce3e3; */
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.search-wrapper {
  max-width: 800px;
  margin: 0 auto;
  padding: 0 20px;
}

.search-input-container {
  position: relative;
  display: flex;
}

.search-input {
  flex: 1;
  height: 40px;
  padding: 0 15px;
  border: none;
  border-radius: 4px 0 0 4px;
  font-size: 16px;
  outline: none;
}

.search-button {
  height: 40px;
  padding: 0 20px;
  background-color: #834278;
  color: white;
  border: none;
  border-radius: 0 4px 4px 0;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.search-button:hover {
  background-color: #411449;
}

.search-suggestions {
  position: absolute; /* 相对于父级 .search-input-container 定位 */
  top: 100%; /* 顶部与父级底部对齐 */
  left: 0; /* 左侧与父级左侧对齐 */
  right: 0; /* 右侧与父级右侧对齐（保证宽度一致） */
  margin-top: 2px; /* 与输入框保持微小间距 */
  background-color: white;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  z-index: 1000; /* 确保不被其他元素遮挡 */
  padding: 5px 0;
  width: 100%; /* 与输入框宽度保持一致 */
  box-sizing: border-box; /* 避免边框导致宽度溢出 */
}

.search-suggestions ul {
  list-style: none;
  margin: 0;
  padding: 0;
}

.search-suggestions li {
  padding: 8px 15px;
  cursor: pointer;
  transition: background-color 0.2s;
  color: #666;
}

.search-suggestions li:hover {
  background-color: #f5f7fa;
}

.result-area {
  max-width: 1200px;
  margin: 30px auto;
  padding: 0 20px;
}

.filter-options {
  margin-bottom: 20px;
}

.filter-type {
  display: flex;
  gap: 10px;
}

.filter-type button {
  padding: 8px 15px;
  background-color: white;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.filter-type button.active {
  background-color: #70316d;;
  color: white;
  border-color: #70316d;
}

.article-list {
  display: grid;
  grid-template-columns: 1fr;
  gap: 20px;
}

.article-card {
  background-color: #fce3e3;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s;
}

.article-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.article-header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 15px;
}

.author-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
}

.author-info {
  display: flex;
  flex-direction: column;
}

.author-name {
  font-weight: bold;
  color: #333;
}

.publish-time {
  font-size: 12px;
  color: #999;
}

.top-tag,
.recommend-tag {
  margin-left: auto;
  padding: 2px 5px;
  font-size: 12px;
  border-radius: 3px;
}

.top-tag {
  background-color: #e6a23c;
  color: white;
}

.recommend-tag {
  background-color: #409eff;
  color: white;
}

.article-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 10px;
  color: #333;
  cursor: pointer;
  transition: color 0.3s;
}

.article-title:hover {
  color: #409eff;
}

.article-summary {
  color: #666;
  line-height: 1.6;
  margin-bottom: 15px;
  max-height: 3.2em;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.article-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  align-items: center;
  color: #999;
}

.tag {
  padding: 2px 8px;
  background-color: #f0f2f5;
  border-radius: 4px;
  font-size: 12px;
  color: #606266;
}

.view-count,
.like-count,
.comment-count {
  display: flex;
  align-items: center;
  font-size: 14px;
}

.load-more {
  text-align: center;
  margin: 30px 0;
}

.load-more-btn {
  padding: 10px 20px;
  background-color: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.load-more-btn:hover {
  background-color: #3080fe;
}

.no-more-results {
  text-align: center;
  margin: 30px 0;
  color: #999;
}
</style>
    